import { ChildProcess, exec, execSync } from 'child_process'
import path from 'path'
import fs from 'fs'
import { app } from 'electron'
const logsDir = path.join(app.getPath('userData'), 'logs')
if (!fs.existsSync(logsDir)) {
  fs.mkdirSync(logsDir, { recursive: true })
}

// 获取应用相关路径
function getAppPaths(): {
  nginxPath: string
  nginxDir: string
  nginxTempDir: string
  staticDir: string
} {
  const userDataPath = app.getPath('userData')
  return {
    nginxPath: path.join(
      process.resourcesPath,
      'nginx',
      process.platform === 'win32' ? 'nginx.exe' : 'nginx'
    ),
    nginxDir: path.join(process.resourcesPath, 'nginx'),
    nginxTempDir: path.join(userDataPath, 'nginx_temp'), // 用户数据目录下的临时目录
    staticDir: path.join(process.resourcesPath, 'static') // 静态资源目录
  }
}

// 替代 ensureDir
function ensureDirSync(dirPath): void {
  try {
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath, { recursive: true })
    }
  } catch (err) {
    console.error('创建目录失败:', err)
    throw err
  }
}

// 替代 copy
function copyDirSync(src, dest): void {
  ensureDirSync(dest)

  const entries = fs.readdirSync(src, { withFileTypes: true })

  for (const entry of entries) {
    const srcPath = path.join(src, entry.name)
    const destPath = path.join(dest, entry.name)

    if (entry.isDirectory()) {
      copyDirSync(srcPath, destPath)
    } else {
      fs.copyFileSync(srcPath, destPath)
    }
  }
}

// 解压静态资源
function extractStaticFiles(): string | null {
  const sourceDir = path.join(process.resourcesPath, 'app.asar', 'out', 'renderer')
  const targetDir = path.join(process.resourcesPath, 'static')

  try {
    console.log('正在解压静态资源...')
    console.log('源目录:', sourceDir)
    console.log('目标目录:', targetDir)

    // 检查源目录是否存在
    if (!fs.existsSync(sourceDir)) {
      throw new Error(`源目录不存在: ${sourceDir}`)
    }

    // 执行复制
    copyDirSync(sourceDir, targetDir)

    console.log('静态资源解压完成:', targetDir)
    return targetDir
  } catch (err) {
    console.error('解压静态资源失败:', err)
    return null
  }
}

// 确保所有必要目录存在
function ensureDirectories(): boolean {
  const paths = getAppPaths()

  // 创建Nginx需要的临时目录结构
  const tempSubDirs = ['client_body_temp', 'proxy_temp', 'fastcgi_temp', 'uwsgi_temp', 'scgi_temp']

  try {
    // 创建基础临时目录
    fs.existsSync(paths.nginxTempDir)

    // 创建子目录
    tempSubDirs.forEach((dir) => {
      fs.mkdirSync(path.join(paths.nginxTempDir, dir), { recursive: true })
    })

    return true
  } catch (err) {
    console.error('创建目录失败:', err)
    return false
  }
}

// 生成动态Nginx配置
function generateNginxConfig(): string {
  const paths = getAppPaths()
  const configContent = `
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    # 使用用户数据目录下的临时路径
    client_body_temp_path  "${path.join(paths.nginxTempDir, 'client_body_temp').replace(/\\/g, '/')}";
    proxy_temp_path       "${path.join(paths.nginxTempDir, 'proxy_temp').replace(/\\/g, '/')}";
    fastcgi_temp_path     "${path.join(paths.nginxTempDir, 'fastcgi_temp').replace(/\\/g, '/')}";
    uwsgi_temp_path       "${path.join(paths.nginxTempDir, 'uwsgi_temp').replace(/\\/g, '/')}";
    scgi_temp_path        "${path.join(paths.nginxTempDir, 'scgi_temp').replace(/\\/g, '/')}";

    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       8521;
        server_name  localhost;

        location / {
            root   "${paths.staticDir.replace(/\\/g, '/')}";
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
    }
}
  `

  const configPath = path.join(paths.nginxDir, 'conf', 'nginx.conf')
  fs.writeFileSync(configPath, configContent)
  return configPath
}
const logFilePath = path.join(logsDir, 'nginx.log')
// 函数logToFile用于将日志信息写入文件
function logToFile(message, level = 'INFO'): void {
  // 获取当前时间戳
  const timestamp = new Date().toISOString()
  // 构造日志信息
  const logMessage = `[${timestamp}] [${level}] ${message}\n`
  // 将日志信息写入文件
  fs.appendFile(logFilePath, logMessage, (err) => {
    // 如果写入失败，输出错误信息
    if (err) console.error('写入日志失败:', err)
  })
}

function startNginx(): ChildProcess {
  if (!ensureDirectories()) {
    throw new Error('无法创建必要的目录')
  }
  extractStaticFiles()
  const paths = getAppPaths()
  const configPath = generateNginxConfig()

  const command = `"${paths.nginxPath}" -p "${paths.nginxDir}" -c "${configPath}"`
  console.log('启动命令:', command)
  logToFile(`启动命令: ${command}`)
  const nginxProcess = exec(command)

  nginxProcess?.stdout?.on('data', (data) => {
    console.log(`Nginx: ${data}`)
    logToFile(`Nginx: ${data}`)
  })
  nginxProcess?.stderr?.on('data', (data) => {
    console.error(`Nginx Error: ${data}`)
    logToFile(`Nginx Error: ${data}`, 'ERROR')
  })

  return nginxProcess
}

export function stropNginx(): void {
  const path = getAppPaths()
  if (!path.nginxDir) return

  try {
    // 使用 Nginx 自带的停止命令
    execSync(`"${path.nginxPath}" -p "${path.nginxDir}" -s stop`, {
      stdio: 'ignore',
      timeout: 2000 // 2秒超时
    })
    console.log('Nginx closed')
  } catch (err) {
    console.warn('Nginx storp fail, try to kill it', err)
    // 如果停止命令失败，强制终止进程
    try {
      if (process.platform === 'win32') {
        // Windows 系统
        execSync(`taskkill /F /T /IM nginx.exe`, { stdio: 'ignore' })
      } else {
        // Linux/macOS 系统
        execSync(`pkill -f nginx`, { stdio: 'ignore' })
      }
      console.log('Nginx force closed')
    } catch (killError) {
      console.error('force closed Nginx fail:', killError)
    }
  }
}
export default startNginx
